package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 新增数据时填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 1.严格填充，如果值已经存在不会填充
//        strictInsertFill(metaObject, "createTime", Date.class, new Date());
//        strictInsertFill(metaObject, "createBy", String.class, getCurrentUserId());
//        strictInsertFill(metaObject, "updateTime", Date.class, new Date());
//        strictInsertFill(metaObject, "updateBy", String.class, getCurrentUserId());

        // 2.普通填充，如果值已经存在仍然会填充
        setFieldValByName("createTime", new Date(), metaObject);
        setFieldValByName("createBy", getCurrentUserId(), metaObject);
        setFieldValByName("updateTime", new Date(), metaObject);
        setFieldValByName("updateBy", getCurrentUserId(), metaObject);
    }

    /**
     * 修改数据时填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateTime", new Date(), metaObject);
        setFieldValByName("updateBy", getCurrentUserId(), metaObject);
    }

    /**
     * 获取当前用户ID
     *
     * @return
     */
    private String getCurrentUserId() {
        return String.valueOf(SecurityUtils.getUserId());
    }
}
